﻿Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml
Imports Mysoft.Map.Data
Imports System.Web.UI.Design
Imports System.Text




<ToolboxData("<{0}:ProjDDTree3 runat=server></{0}:ProjDDTree3>")> Public Class ProjDDTree3
    Inherits Mysoft.Map.Application.Controls.AppDropDownTree

    Private _datatable As DataTable

    Private _textControl As System.Web.UI.WebControls.TextBox
    Private _valueControl As System.Web.UI.WebControls.TextBox
    Private _levelControl As System.Web.UI.WebControls.TextBox
    Private _levelTypeControl As System.Web.UI.WebControls.TextBox

    '翻译应用子系统代码
    Private Function GetApplySysCode() As String
        Dim strRtn As String

        Select Case Me.ApplySys
            Case ApplySyss.销售管理
                strRtn = "0101"
            Case ApplySyss.客户服务管理
                strRtn = "0102"
            Case ApplySyss.会员管理
                strRtn = "0103"
            Case ApplySyss.租赁管理
                strRtn = "0104"
            Case ApplySyss.成本管理
                strRtn = "0201"
            Case ApplySyss.项目进度
                strRtn = "0202"
            Case ApplySyss.投资分析
                strRtn = "0203"
            Case ApplySyss.采购招投标
                strRtn = "0204"
            Case Else
                strRtn = "0101"
        End Select

        Return strRtn
    End Function

    Public Enum DefaultValueTypes
        ProjGUID = 0
    End Enum

    Public Enum DisplayHiberarchys
        Project = 0
        Building = 1
        Company = 2
    End Enum

    Public Enum ApplySyss
        销售管理 = 1
        客户服务管理 = 2
        会员管理 = 3
        租赁管理 = 4
        投资分析 = 5
        项目进度 = 6
        采购招投标 = 7
        成本管理 = 8
    End Enum


    Public Event ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs)

#Region "定义属性"

    <Browsable(False), Category("Data"), Description("控件数据源。")> Overridable Property [DataTable]() As DataTable
        Get
            Return _datatable
        End Get
        Set(ByVal value As DataTable)
            _datatable = value
        End Set
    End Property

    <Browsable(False), Category("Data")> Overrides Property CssClass() As String
        Get
            If MyBase.CssClass Is String.Empty Then
                Return "ProjDDTree"
            End If
            Return MyBase.CssClass
        End Get
        Set(ByVal value As String)
            MyBase.CssClass = value
        End Set
    End Property

    <Browsable(False)> Overridable Property [Value]() As String
        Get
            If Not FindControl(Me.ID & "_txtValue") Is Nothing AndAlso TypeOf FindControl(Me.ID & "_txtValue") Is TextBox Then
                Return CType(FindControl(Me.ID & "_txtValue"), TextBox).Text.Trim
            End If
            Return String.Empty
        End Get

        Set(ByVal Value As String)
            If Not FindControl(Me.ID & "_txtValue") Is Nothing AndAlso TypeOf FindControl(Me.ID & "_txtValue") Is TextBox Then
                CType(FindControl(Me.ID & "_txtValue"), TextBox).Text = Value.ToLower
            End If
        End Set

    End Property

    <Browsable(False), Category("Data"), Description("为列表项提供文本内容的数据源字段。")> Overridable ReadOnly Property DataTextField() As String
        Get
            If Not ViewState("DataTextField") Is Nothing Then
                Return CStr(ViewState("DataTextField"))
            End If
            Return "LevelName"
        End Get
        'Set(ByVal Value As String)
        '    ViewState("DataTextField") = Value
        'End Set
    End Property

    <Browsable(False), Category("Data"), Description("为各列表项提供值的数据源字段。")> Overridable ReadOnly Property DataValueField() As String
        Get
            If Not ViewState("DataValueField") Is Nothing Then
                Return CStr(ViewState("DataValueField"))
            End If
            Return "LevelGUID"
        End Get
        'Set(ByVal Value As String)
        '    ViewState("DataValueField") = Value
        'End Set
    End Property

    '自定义过滤条件
    <Category("Data"), Description("自定义数据过滤条件，替换 SQL 语句中的 ""5=5""。"), DefaultValue("")> Property CustomFilter() As String
        Get
            If ViewState("CustomFilter") Is Nothing Then
                Return ""
            End If
            Return Convert.ToString(ViewState("CustomFilter"))
        End Get
        Set(ByVal Value As String)
            If Value Is Nothing Then
                Value = ""
            End If
            ViewState("CustomFilter") = Value
        End Set
    End Property

    <Category("Data"), Description("设置项目GUID对应英文字段名，默认为[ProjGUID]")> Overridable Property ProjField() As String
        Get
            If Not ViewState("ProjField") Is Nothing Then
                Return CStr(ViewState("ProjField"))
            End If
            Return "ProjGUID"
        End Get
        Set(ByVal Value As String)
            ViewState("ProjField") = Value
        End Set
    End Property

    <Category("Data"), Description("设置楼栋GUID对应英文字段名，默认为[BldGUID]")> Overridable Property BldField() As String
        Get
            If Not ViewState("BldField") Is Nothing Then
                Return CStr(ViewState("BldField"))
            End If
            Return "BldGUID"
        End Get
        Set(ByVal Value As String)
            ViewState("BldField") = Value
        End Set
    End Property

    <Browsable(False), Category("Data"), Description("为列表项提供级别的数据源字段。")> Overridable ReadOnly Property DataLevelField() As String
        Get
            If Not ViewState("DataLevelField") Is Nothing Then
                Return CStr(ViewState("DataLevelField"))
            End If
            Return "LevelCode"
        End Get
        'Set(ByVal Value As String)
        '    ViewState("DataLevelField") = Value
        'End Set
    End Property

    <Browsable(False), Category("Appearance"), Description("控件图标的 Url。"), DefaultValue(""), Editor("System.Web.UI.Design.ImageUrlEditor", GetType(System.Drawing.Design.UITypeEditor))> Overridable Property Icon() As String
        Get
            If Not ViewState("Icon") Is Nothing Then
                Return CStr(ViewState("Icon"))
            End If
            Return ""
        End Get
        Set(ByVal Value As String)
            ViewState("Icon") = Value
        End Set
    End Property

    <Category("Data"), Description("是否显示图标（默认：True）。"), DefaultValue(True)> Overridable Property EnableIcon() As Boolean
        Get
            If Not ViewState("EnableIcon") Is Nothing Then
                Return CBool(ViewState("EnableIcon"))
            End If
            Return True
        End Get
        Set(ByVal Value As Boolean)
            ViewState("EnableIcon") = Value
        End Set
    End Property


    <Category("Data"), Description("单击列表项，是否展开下级（默认：True）。"), DefaultValue(True)> Overridable Property ClickExpand() As Boolean
        Get
            If Not ViewState("ClickExpand") Is Nothing Then
                Return CBool(ViewState("ClickExpand"))
            End If
            Return True
        End Get
        Set(ByVal Value As Boolean)
            ViewState("ClickExpand") = Value
        End Set
    End Property

    <Category("Data"), Description("初始展开级别（默认：2级）。"), DefaultValue(True)> Overridable Property DefaultExpandLevel() As Integer
        Get
            If Not ViewState("DefaultExpandLevel") Is Nothing Then
                Return CInt(ViewState("DefaultExpandLevel"))
            End If
            Return 2
        End Get
        Set(ByVal Value As Integer)
            ViewState("DefaultExpandLevel") = Value
        End Set
    End Property

    <Category("Data"), Description("下拉框显示行数，超出显示滚动条（默认：10）。"), DefaultValue(True)> Overridable Property MaxRows() As Integer
        Get
            If Not ViewState("MaxRows") Is Nothing Then
                Return CInt(ViewState("MaxRows"))
            End If
            Return 10
        End Get
        Set(ByVal Value As Integer)
            ViewState("MaxRows") = Value
        End Set
    End Property


    <Browsable(False), Category("Data"), Description("根节点显示文本。")> Overridable ReadOnly Property RootText() As String
        Get
            If Not ViewState("RootText") Is Nothing Then
                Return CStr(ViewState("RootText"))
            End If
            Return String.Empty
        End Get
        'Set(ByVal Value As String)
        '    ViewState("RootText") = Value
        'End Set
    End Property

    <Browsable(False), Category("Data"), Description("根节点值。")> Overridable ReadOnly Property RootValue() As String
        Get
            If Not ViewState("RootValue") Is Nothing Then
                Return CStr(ViewState("RootValue"))
            End If
            Return String.Empty
        End Get
        'Set(ByVal Value As String)
        '    ViewState("RootValue") = Value
        'End Set
    End Property

    <Browsable(False), Category("Data"), Description("查询条件。")> Overridable ReadOnly Property QueryReplace() As String
        Get
            If Not ViewState("QueryReplace") Is Nothing Then
                Return CStr(ViewState("QueryReplace"))
            End If
            Return ""
        End Get
        'Set(ByVal Value As String)
        '    ViewState("QueryReplace") = Value
        'End Set
    End Property

    <Category("Data"), Description("设置公司GUID默认值（不设置则默认当前公司）")> Overridable Property DefaultBUGUID() As String
        Get
            If Not ViewState("DefaultBUGUID") Is Nothing Then
                Return CStr(ViewState("DefaultBUGUID"))
            End If
            Return ""
        End Get
        Set(ByVal Value As String)
            ViewState("DefaultBUGUID") = Value
        End Set
    End Property


    <Category("Data"), Description("设置显示层次：Project 显示到项目（默认）；Building 显示到楼栋；Company 显示到公司")> Overridable Property DisplayHiberarchy() As DisplayHiberarchys
        Get
            If Not ViewState("DisplayHiberarchy") Is Nothing Then
                Return CStr(ViewState("DisplayHiberarchy"))
            End If
            Return DisplayHiberarchys.Project
        End Get
        Set(ByVal Value As DisplayHiberarchys)
            ViewState("DisplayHiberarchy") = Value
        End Set
    End Property

    <Category("Data"), Description("设置调用此控件的应用子系统")> Overridable Property ApplySys() As ApplySyss
        Get
            If Not ViewState("ApplySys") Is Nothing Then
                Return CStr(ViewState("ApplySys"))
            End If
            Return ApplySyss.销售管理
        End Get
        Set(ByVal Value As ApplySyss)
            ViewState("ApplySys") = Value
        End Set
    End Property

    <Category("Data"), Description("设置是否允许选择所有项目（默认：True）")> Overridable Property IsSelectAll() As Boolean
        Get
            If Not ViewState("IsSelectAll") Is Nothing Then
                Return CBool(ViewState("IsSelectAll"))
            End If
            Return True
        End Get
        Set(ByVal Value As Boolean)
            ViewState("IsSelectAll") = Value
        End Set
    End Property

    <Category("Data"), Description("设置是否使用项目过滤权限（默认：True）")> Overridable Property IsProjRights() As Boolean
        Get
            If Not ViewState("IsProjRights") Is Nothing Then
                Return CBool(ViewState("IsProjRights"))
            End If
            Return True
        End Get
        Set(ByVal Value As Boolean)
            ViewState("IsProjRights") = Value
        End Set
    End Property

    <Category("Data"), Description("设置是否只能选择最末级（默认：False）")> Overridable Property IsSelectLastLevelOnly() As Boolean
        Get
            If Not ViewState("IsSelectLastLevelOnly") Is Nothing Then
                Return CBool(ViewState("IsSelectLastLevelOnly"))
            End If
            Return False
        End Get
        Set(ByVal Value As Boolean)
            ViewState("IsSelectLastLevelOnly") = Value
        End Set
    End Property

    <Browsable(False), Category("Data"), Description("设置记忆功能的类别")> Overridable Property DefaultValueType() As DefaultValueTypes
        Get
            If Not ViewState("DefaultValueType") Is Nothing Then
                Return ViewState("DefaultValueType")
            End If
            Return DefaultValueTypes.ProjGUID
        End Get
        Set(ByVal Value As DefaultValueTypes)
            ViewState("DefaultValueType") = Value
        End Set
    End Property

    <Browsable(False), Category("Data"), Description("设置默认级别类型：公司、项目、楼栋")> Overridable Property DefaultLevelType() As String
        Get
            If Not ViewState("DefaultLevelType") Is Nothing Then
                Return ViewState("DefaultLevelType")
            End If
            Return ""
        End Get
        Set(ByVal Value As String)
            ViewState("DefaultLevelType") = Value
        End Set
    End Property

    <Category("Data"), Description("设置是否启用记忆功能，默认True")> Overridable Property DefaultEnable() As Boolean
        Get
            If Not ViewState("DefaultEnable") Is Nothing Then
                Return ViewState("DefaultEnable")
            End If
            Return True
        End Get

        Set(ByVal Value As Boolean)
            ViewState("DefaultEnable") = Value
        End Set

    End Property

    <Category("Data"), Description("设置是否启用楼栋的租售类型过滤，默认True")> Overridable Property ZslxFiltEnable() As Boolean
        Get
            If Not ViewState("ZslxFiltEnable") Is Nothing Then
                Return ViewState("ZslxFiltEnable")
            End If
            Return True
        End Get

        Set(ByVal Value As Boolean)
            ViewState("ZslxFiltEnable") = Value
        End Set
    End Property

#End Region


#Region "定义属性（前端事件）"

    <Category("Behavior"), Description("控件填充显示内容时触发。"), DefaultValue("")> Overridable Property OnFillContent() As String
        Get
            If Not ViewState("OnFillContent") Is Nothing Then
                Return CStr(ViewState("OnFillContent"))
            End If
            Return String.Empty
        End Get
        Set(ByVal Value As String)
            ViewState("OnFillContent") = Value
        End Set
    End Property

    <Category("Behavior"), Description("前端事件 ondropdown 触发时调用的前端函数名。"), DefaultValue("")> Overridable Property OnDropDown() As String
        Get
            If Not ViewState("OnDropDown") Is Nothing Then
                Return CStr(ViewState("OnDropDown"))
            End If
            Return String.Empty
        End Get
        Set(ByVal Value As String)
            ViewState("OnDropDown") = Value
        End Set
    End Property

    <Category("Behavior"), Description("前端事件 onbeforechange 触发时调用的前端函数名。"), DefaultValue("")> Overridable Property OnBeforeChange() As String
        Get
            If Not ViewState("OnBeforeChange") Is Nothing Then
                Return CStr(ViewState("OnBeforeChange"))
            End If
            Return String.Empty
        End Get
        Set(ByVal Value As String)
            ViewState("OnBeforeChange") = Value
        End Set
    End Property

    <Category("Behavior"), Description("前端事件 onchange 触发时调用的前端函数名。"), DefaultValue("")> Overridable Property OnChange() As String
        Get
            If Not ViewState("OnChange") Is Nothing Then
                Return CStr(ViewState("OnChange"))
            End If
            Return String.Empty
        End Get
        Set(ByVal Value As String)
            ViewState("OnChange") = Value
        End Set
    End Property

    <Category("Behavior"), Description("前端事件 onquery 触发时调用的前端函数名。"), DefaultValue("")> Overridable Property OnQuery() As String
        Get
            If Not ViewState("OnQuery") Is Nothing Then
                Return CStr(ViewState("OnQuery"))
            End If
            Return String.Empty
        End Get
        Set(ByVal Value As String)
            ViewState("OnQuery") = Value
        End Set
    End Property
#End Region


#Region "配置数据"

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        '配置数据
        ConfigureData()
    End Sub

    Private Sub ConfigureData()
        '1、显示模式：到项目(Project)、到楼栋(Bluilding)、到公司（Company）
        Dim strDisplayMode As String
        strDisplayMode = Me.DisplayHiberarchy.ToString("G")

        '设置公司GUID默认值（不设置则默认当前公司）
        Dim strBUGUID As String
        If Not Me.DefaultBUGUID Is Nothing And Me.DefaultBUGUID <> "" Then
            strBUGUID = Me.DefaultBUGUID
        Else
            strBUGUID = Me.Context.Session("BUGUID")
        End If

        '当支持项目或支持楼栋时，数据源不同
        ' 获取应用子系统代码
        Dim strApplySysCode As String = GetApplySysCode()
        Dim strSql As String
        If strDisplayMode.ToUpper = "Project".ToUpper Then      '显示到项目
            strSql = " SELECT Distinct a.LevelCode, a.LevelName,a.LevelFullName, a.LevelGUID, a.ParentCode, a.Level, a.IfEndProj as IfEnd,a.IfEndProj, a.LevelType,a.IsEndCompany,a.IfEndBld,a.ProjGUID,1 as IfQx" & _
                     " FROM vp_Project2Building a,vp_Project2Building b " & _
                     " WHERE a.LevelType<>'楼栋'" & _
                        " AND a.BUGUID='" & strBUGUID & "'" & _
                        " AND b.BUGUID='" & strBUGUID & "'" & _
                        " AND b.LevelType='项目'" & _
                        " AND ((b.LevelCode like a.LevelCode + '.%') OR (b.LevelCode = a.LevelCode))" & _
                        " AND (1=1)" & _
                        " AND (2=2)" & _
                        " AND (3=3)" & _
                        " AND (4=4)" & _
                        " AND (5=5)"

        ElseIf strDisplayMode.ToUpper = "Building".ToUpper Then '显示到楼栋

            strSql = " SELECT Distinct a.LevelCode, a.LevelName,a.LevelFullName, a.LevelGUID, a.ParentCode, a.Level, a.IfEndBld as IfEnd,a.IfEndProj, a.LevelType,a.IsEndCompany,a.IfEndBld,a.ProjGUID,1 as IfQx" & _
                     " FROM vp_Project2Building a,vp_Project2Building b " & _
                     " WHERE a.BUGUID='" & strBUGUID & "'" & _
                        " AND b.BUGUID='" & strBUGUID & "'" & _
                        " AND b.LevelType='项目'" & _
                        " AND ((b.LevelCode like a.LevelCode + '.%') OR (b.LevelCode = a.LevelCode) OR (b.IfEndProj = 1 AND a.LevelCode like b.LevelCode + '.%'))" & _
                        " AND (1=1)" & _
                        " AND (2=2)" & _
                        " AND (3=3)" & _
                        " AND (4=4)" & _
                        " AND (5=5)"

            '售楼系统不出现租赁楼栋
            If Me.ZslxFiltEnable = True Then
                If Me.ApplySys = ApplySyss.销售管理 Then
                    strSql = strSql.Replace("4=4", "case when a.IfEndBld=0 then '出售' else a.Zslx end in ('租售','出售')")
                ElseIf Me.ApplySys = ApplySyss.租赁管理 Then
                    strSql = strSql.Replace("4=4", "case when a.IfEndBld=0 then '出租' else a.Zslx end in ('租售','出租')")
                End If
            End If

        Else                                                 '显示到公司
            strSql = " SELECT Distinct a.LevelCode, a.LevelName,a.LevelFullName, a.LevelGUID, a.ParentCode, a.Level, a.IsEndCompany as IfEnd,a.IfEndProj, a.LevelType,a.IsEndCompany,a.IfEndBld,a.ProjGUID,1 as IfQx" & _
                               " FROM vp_Project2Building a,vp_Project2Building b " & _
                               " WHERE a.LevelType ='公司'" & _
                                  " AND b.LevelType='项目'" & _
                                  " AND ((b.LevelCode like a.LevelCode + '.%') OR (b.LevelCode = a.LevelCode))" & _
                                  " AND (1=1)" & _
                                  " AND (2=2)" & _
                                  " AND (3=3)" & _
                                  " AND (4=4)" & _
                                  " AND (5=5)"
        End If
        strSql &= " ORDER BY a.LevelCode"

        '2、是否可以选择所有项目
        If Me.IsSelectAll = False AndAlso strDisplayMode.ToUpper <> "Company".ToUpper Then
            strSql = strSql.Replace("1=1", "a.LevelType<>'公司'")
        End If

        '2、用户项目过滤
        Dim strProjStr As String = ""
        If Me.IsProjRights Then
            '使用项目过滤
            If strDisplayMode.ToUpper = "Company".ToUpper Then
                strProjStr = MyDB.GetProjectString(Me.Context.Session("UserGUID"), "", strApplySysCode, True).ToLower()
            Else
                strProjStr = MyDB.GetProjectString(Me.Context.Session("UserGUID"), strBUGUID, strApplySysCode, True).ToLower()
            End If

            Dim strProjFilt As String = IIf(strProjStr = "", "1=2", "b.ProjGUID IN (" & strProjStr & ")")
            strSql = strSql.Replace("2=2", strProjFilt)
        Else
            '取当前系统下的所有项目,以及共享项目
            Dim strProjFilt As String = "(b.ProjGUID IN (select ProjGUID from ek_Project where buguid ='" & strBUGUID & "' AND ApplySys like '%," & strApplySysCode & ",%'))"
            strSql = strSql.Replace("2=2", strProjFilt)
        End If

        '3  分系统过滤(只有客服系统才能包含共享项目以及所属楼栋)
        If ApplySys <> ApplySyss.客户服务管理 Then
            strSql = strSql.Replace("3=3", "a.IfShare = 0 AND b.IfShare=0")
        End If

        '4. 用户自定义过滤条件
        If Me.CustomFilter <> "" Then
            strSql = strSql.Replace("5=5", Me.CustomFilter)
        End If

        Dim dtTmp As DataTable = MyDB.GetDataTable(strSql)
        Me.DataTable = dtTmp
        Me.DataTable.TableName = "dt"
        Me.DataTable.DataSet.DataSetName = "ds"

        '5 标识哪些上级项目是没有权限的
        If dtTmp.Rows.Count > 0 Then
            Dim i As Int16 = 0
            For i = 0 To dtTmp.Rows.Count - 1
                With dtTmp.Rows(i)
                    If .Item("LevelType").ToString <> "公司" Then
                        If strProjStr.IndexOf(.Item("ProjGUID").ToString) = -1 Then
                            .Item("IfQx") = 0
                        End If
                    End If
                End With
            Next
        End If


        '设定默认值
        SetDefaultValue(dtTmp)

    End Sub

    '设置默认值
    Public Sub SetDefaultValue(ByVal dtTmp As DataTable)

        If dtTmp.Rows.Count = 0 Then
            Me.DefaultLevel = ""
            Me.DefaultValue = ""
            Me.DefaultText = ""
            Me.DefaultLevelType = ""
            Me.Value = ""
        Else

            '处理默认值
            Dim strDefGUID As String = ""
            If Me.Value = "" Or Me.Value Is Nothing Then
                Dim MyGeneral As New Mysoft.Map.Utility.General

                '如果启用记忆功能，则取记忆值
                If Me.DefaultEnable = True Then
                    strDefGUID = MyGeneral.GetCurrArg(Me.DefaultValueType.ToString("G"))
                End If

            Else
                strDefGUID = Me.Value
            End If

            '如果是记忆的是楼栋，则取楼栋所属的项目
            Dim strFilter As String = ""


            '设置公司GUID默认值（不设置则默认当前公司）
            Dim strBUGUID As String
            If Not Me.DefaultBUGUID Is Nothing And Me.DefaultBUGUID <> "" Then
                strBUGUID = Me.DefaultBUGUID
            Else
                strBUGUID = Me.Context.Session("BUGUID")
            End If


            Dim strSQL As String
            If strDefGUID <> "" Then
                strSQL = " SELECT Top 1 Case When LevelType='楼栋' Then ProjGUID Else LevelGUID End as LevelGUID,LevelType" & _
                         " FROM vp_Project2Building " & _
                         " WHERE LevelGUID='" & strDefGUID & "'" & _
                            " AND BUGUID='" & strBUGUID & "'"
                Dim dtTest As DataTable = MyDB.GetDataTable(strSQL)
                If dtTest.Rows.Count > 0 Then
                    strDefGUID = dtTest.Rows(0).Item("LevelGUID").ToString
                    If dtTest.Rows(0).Item("LevelType").ToString = "楼栋" AndAlso Me.IsSelectLastLevelOnly = True Then
                        strFilter = "ProjGUID='" & strDefGUID & "'"
                    Else
                        strFilter = "LevelGUID='" & strDefGUID & "'"
                    End If
                Else
                    strDefGUID = ""
                End If

            End If

            '如果只显示最末级
            If Me.IsSelectLastLevelOnly = True Then
                strFilter &= IIf(strFilter <> "", " AND ", "") & "IfEnd = 1"
            End If

            '找到对应行
            Dim dvTmp As DataView = dtTmp.DefaultView
            dvTmp.RowFilter = strFilter
            If dvTmp.Count > 0 Then
                Me.DefaultLevel = dvTmp(0).Item("LevelCode").ToString
                Me.DefaultValue = dvTmp(0).Item("LevelGUID").ToString
                Me.DefaultText = dvTmp(0).Item("LevelName").ToString
                Me.DefaultLevelType = dvTmp(0).Item("LevelType").ToString
                Me.Value = dvTmp(0).Item("LevelGUID").ToString
            Else
                strFilter = ""
                If Me.IsSelectLastLevelOnly = True Then strFilter = "IfEnd = 1"
                dvTmp.RowFilter = strFilter

                If dvTmp.Count > 0 Then
                    Me.DefaultLevel = dvTmp(0).Item("LevelCode").ToString
                    Me.DefaultValue = dvTmp(0).Item("LevelGUID").ToString
                    Me.DefaultText = dvTmp(0).Item("LevelName").ToString
                    Me.DefaultLevelType = dvTmp(0).Item("LevelType").ToString
                    Me.Value = dvTmp(0).Item("LevelGUID").ToString
                Else
                    Me.DefaultLevel = ""
                    Me.DefaultValue = ""
                    Me.DefaultText = ""
                    Me.DefaultLevelType = ""
                    Me.Value = ""
                End If

            End If

        End If

        _textControl.Text = Me.DefaultText
        _valueControl.Text = Me.DefaultValue
        _levelControl.Text = Me.DefaultLevel
        _levelTypeControl.Text = Me.DefaultLevelType

    End Sub


#End Region


#Region "控件输出"

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        RenderBeginTag(writer)
        RenderContents(writer)
        RenderEndTag(writer)
    End Sub


    '输出控件开始标记
    Public Overrides Sub RenderBeginTag(ByVal writer As System.Web.UI.HtmlTextWriter)

        writer.Write("<table class=""" & Me.CssClass & """ style=""table-layout:fixed;display:inline;background-color:white;")

        '控件宽度
        writer.Write("width:" & IIf(Me.Width.IsEmpty, "100%", Me.Width.ToString) & ";")
        writer.Write(""" cellspacing=""0"" cellpadding=""0"" ID=""" & Me.ID & """")

        '属性
        writer.Write(" datatextfield=""" & System.Web.HttpUtility.HtmlEncode(Me.DataTextField) & """")
        writer.Write(" datavaluefield=""" & System.Web.HttpUtility.HtmlEncode(Me.DataValueField) & """")
        writer.Write(" datalevelfield=""" & System.Web.HttpUtility.HtmlEncode(Me.DataLevelField) & """")

        writer.Write(" clickexpand=""" & IIf(Me.ClickExpand, "true", "false") & """")
        writer.Write(" defaultexpandlevel=""" & Me.DefaultExpandLevel & """")
        writer.Write(" enabled=""" & IIf(Me.Enabled, "true", "false") & """")
        writer.Write(" maxrows=""" & Me.MaxRows & """")

        If Me.RootText <> "" Then
            writer.Write(" roottext=""" & System.Web.HttpUtility.HtmlEncode(Me.RootText) & """")
            writer.Write(" rootvalue=""" & System.Web.HttpUtility.HtmlEncode(Me.RootValue) & """")
        End If

        If Me.Icon <> "" Then
            writer.Write(" icon=""" & System.Web.HttpUtility.HtmlEncode(Me.Icon) & """")
        End If

        writer.Write(" enableicon=""" & Me.EnableIcon.ToString.ToLower & """")

        If Me.QueryReplace <> "" Then
            writer.Write(" queryreplace=""" & System.Web.HttpUtility.HtmlEncode(Me.QueryReplace) & """")
        End If
        writer.Write(" isselectlastlevelonly=""" & Me.IsSelectLastLevelOnly.ToString.ToLower & """")
        writer.Write(" isselectall=""" & Me.IsSelectAll.ToString.ToLower & """")
        writer.Write(" displayhiberarchy=""" & System.Web.HttpUtility.HtmlEncode(Me.DisplayHiberarchy.ToString("G")) & """")
        writer.Write(" defaultvaluetype=""" & System.Web.HttpUtility.HtmlEncode(Me.DefaultValueType.ToString("G")) & """")

        writer.Write(" applysyscode=""" & System.Web.HttpUtility.HtmlEncode(GetApplySysCode()) & """")
        writer.Write(" ProjField=""" & System.Web.HttpUtility.HtmlEncode(Me.ProjField) & """")
        writer.Write(" BldField=""" & System.Web.HttpUtility.HtmlEncode(Me.BldField) & """")

        '事件
        If Me.OnFillContent <> "" Then writer.Write(" onfillcontent=""" & System.Web.HttpUtility.HtmlEncode(Me.OnFillContent) & """")
        If Me.OnDropDown <> "" Then writer.Write(" ondropdown=""" & System.Web.HttpUtility.HtmlEncode(Me.OnDropDown) & """")
        If Me.OnBeforeChange <> "" Then writer.Write(" onbeforechange=""" & System.Web.HttpUtility.HtmlEncode(Me.OnBeforeChange) & """")
        If Me.OnChange <> "" Then writer.Write(" onchange=""" & System.Web.HttpUtility.HtmlEncode(Me.OnChange) & """")
        writer.Write(" onquery=""" & System.Web.HttpUtility.HtmlEncode(Me.OnQuery) & """")

        '其它属性
        Dim strAttr As String
        For Each strAttr In Attributes.Keys
            writer.Write(" " & strAttr & "=""" & System.Web.HttpUtility.HtmlEncode(Attributes.Item(strAttr)) & """")
        Next

        writer.Write(">")
        writer.Write("<col><col width=18>")
        writer.Write("<tr>")
    End Sub

    Protected Overrides Sub RenderContents(ByVal writer As System.Web.UI.HtmlTextWriter)
        '控件内容
        writer.Write("<td onclick=""if (event.srcElement.tagName == 'NOBR' || event.srcElement.name == '_spanOut') " & Me.ID & "_imgSelect.click();""><span name=""_spanOut"" style=""padding-left:5px;BORDER: #7b9ebd 1px solid; FONT-SIZE: 9pt; BORDER-RIGHT: none; WIDTH: 100%; FONT-FAMILY: 宋体, Tahoma, Verdana, Arial; HEIGHT: 19px;cursor:default;"">")
        RenderContent(writer)
        writer.Write("</span></td>")

        '控件下拉按钮
        RenderDropDown(writer)

        '生成子控件
        Me.EnsureChildControls()
        MyBase.RenderContents(writer)
    End Sub

    '输出控件显示内容
    Protected Overridable Sub RenderContent(ByVal writer As System.Web.UI.HtmlTextWriter)
        '下拉框选中项
        If _textControl.Text <> "" Then
            If Me.Icon <> "" Then
                writer.Write("<img src=""" & Me.Icon & """ style=""height:16px;width:16px;vertical-align:middle;margin-left:2px;margin-right:5px;"">")
            End If
            writer.Write("<span style=""cursor:hand;color:blue;text-decoration:underline;"">" & System.Web.HttpUtility.HtmlEncode(_textControl.Text) & "</span>")
        End If
    End Sub

    '输出控件下拉图标
    Protected Overridable Sub RenderDropDown(ByVal writer As System.Web.UI.HtmlTextWriter)
        writer.Write("<td><img name=""" & Me.ID & "_imgSelect"" onmouseover=""if (!disabled) src='/_imgs/selectOn.gif';"" onmouseout=""if (!disabled) src='/_imgs/selectOff.gif';"" style=""cursor:hand;"" align=""absmiddle"" src=""/_imgs/selectOff.gif""")
        '下拉事件
        writer.Write(" onclick=""" & Me.ID & ".dropDown()""")
        writer.Write("></td></tr>")

        writer.Write("<tr style=""display:none""><td>")
        writer.Write("<xml id=""_" & Me.ID & "_Xml"">")

        '配置数据
        Dim dtTemp As DataTable
        dtTemp = Me.DataTable
        If Not dtTemp Is Nothing Then
            Dim xmlDoc As New XmlDocument
            Dim xmlN As XmlNode
            Dim xmlAttr As XmlAttribute
            Dim i As Integer
            Dim j As Integer

            xmlDoc.LoadXml("<datasource/>")
            For i = 0 To dtTemp.Rows.Count - 1
                xmlN = xmlDoc.CreateElement("item")
                For j = 0 To dtTemp.Columns.Count - 1
                    xmlAttr = xmlDoc.CreateAttribute(dtTemp.Columns(j).ColumnName)
                    xmlAttr.Value = dtTemp.Rows(i).Item(j).ToString
                    xmlN.Attributes.Append(xmlAttr)
                Next
                xmlDoc.DocumentElement.AppendChild(xmlN)
            Next

            writer.Write(xmlDoc.OuterXml)
        End If

        writer.Write("</xml>")
        writer.Write("</td><td>")
    End Sub

    '输出控件结束标记
    Public Overrides Sub RenderEndTag(ByVal writer As System.Web.UI.HtmlTextWriter)
        writer.Write("</td></tr></table>")
    End Sub


    '创建子控件，用于保存选中的值和文本
    Protected Overrides Sub CreateChildControls()
        Controls.Clear()
        ClearChildViewState()

        _textControl = New System.Web.UI.WebControls.TextBox
        _textControl.ID = Me.ID & "_txtText"
        _textControl.Text = DefaultText
        _textControl.Style.Add("display", "none")
        Controls.Add(_textControl)

        _valueControl = New System.Web.UI.WebControls.TextBox
        _valueControl.ID = Me.ID & "_txtValue"
        _valueControl.Text = DefaultValue
        _valueControl.Style.Add("display", "none")
        AddHandler _valueControl.TextChanged, AddressOf _ValueChanged
        Controls.Add(_valueControl)


        _levelControl = New System.Web.UI.WebControls.TextBox
        _levelControl.ID = "txtDefLevel"
        _levelControl.Text = DefaultLevel
        _levelControl.Style.Add("display", "none")
        Controls.Add(_levelControl)

        _levelTypeControl = New System.Web.UI.WebControls.TextBox
        _levelTypeControl.ID = "txtDefLevelType"
        _levelTypeControl.Text = DefaultLevelType
        _levelTypeControl.Style.Add("display", "none")
        Controls.Add(_levelTypeControl)

        TrackViewState()
        ChildControlsCreated = True
    End Sub

#End Region


#Region "其它"

    Private Sub _ValueChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim txtValue As System.Web.UI.WebControls.TextBox

        txtValue = CType(sender, System.Web.UI.WebControls.TextBox)

        Me.Value = txtValue.Text

        RaiseEvent ValueChanged(sender, e)
    End Sub


#End Region


End Class

Public Class ProjDDTreeDesigner3
    Inherits ControlDesigner

    Public Overrides Function GetDesignTimeHtml() As String
        Dim ctl As Mysoft.Map.Application.Controls.AppDropDownTree = CType(Me.Component, Mysoft.Map.Application.Controls.AppDropDownTree)
        Dim sb As New StringBuilder

        sb.Append("<table class=""dropdowntree"" style=""table-layout:fixed;")
        sb.Append("width:" & IIf(ctl.Width.IsEmpty, "100%", ctl.Width.ToString) & ";"" cellspacing=""0"" cellpadding=""0"" ID=""" & Me.ID & """>")

        sb.Append("<col><col width=18>")
        sb.Append("<tr><td><span style=""BORDER: #7b9ebd 1px solid; FONT-SIZE: 9pt; BORDER-RIGHT: none; WIDTH: 100%; FONT-FAMILY: 宋体, Tahoma, Verdana, Arial; HEIGHT: 19px;cursor:default;"">")
        sb.Append("</span></td>")
        sb.Append("<td><img style=""cursor:hand;"" align=""absmiddle"" src=""/_imgs/selectOff.gif""></td>")
        sb.Append("</tr></table>")

        Return sb.ToString
    End Function

End Class



